package fun.xinnix.service;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import fun.xinnix.annotation.Log;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class TestService {

    @Log("无返回日志")
    public void testLogAdvice() {
        for (int i = 0; i < 10; i++) {

        }
        try {
            Thread.sleep(1000 * 3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Log("有返回日志")
    public List<Integer> testLogAdviceResult(Long id, String name) {
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            result.add(i);
        }
        try {
            Thread.sleep(1000 * 3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int i = 1 / 0;
        return result;
    }

    public void convertPdf(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            PdfReader pdfReader = new PdfReader(file.getInputStream());
            int pages = pdfReader.getNumberOfPages();
            // 设置日期格式
            for (int i = 1; i <= pages; i++) {
                PdfReader reader = new PdfReader(file.getInputStream());
                Document doc = new Document();
                // 每个pdf命名规则：时间戳（2019109143408）+"-"+顺序编号（i）
                String pdfName = "D:/test/" + i + "-" + originalFilename;
                PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(pdfName));
                doc.open();
                PdfContentByte cb = writer.getDirectContent();
                doc.newPage();
                cb.addTemplate(writer.getImportedPage(reader, i), 0, 0);
                doc.close();
                writer.close();
                reader.close();
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }
}
